package com.djmw.mouse.service.account;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import com.djmw.mouse.entity.LoginUseOnlyUser;
import com.djmw.mouse.entity.User;
import com.djmw.mouse.repository.LoginUseOnlyUserDao;
import com.djmw.mouse.service.account.ShiroDbRealm.ShiroUser;

/**
 * 用户管理类.
 * 
 * @author michael
 */
// Spring Service Bean的标识.
@Component
@Transactional(readOnly = true)
public class LoginUseOnlyAccountService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	protected static Logger logger = LoggerFactory.getLogger(LoginUseOnlyAccountService.class);

	private LoginUseOnlyUserDao loginUseOnlyUserDao;

	public List<LoginUseOnlyUser> getAllUser() {
		return (List<LoginUseOnlyUser>) loginUseOnlyUserDao.findAll();
	}

	public LoginUseOnlyUser getUser(Long id) {
		return loginUseOnlyUserDao.findOne(id);
	}

	public LoginUseOnlyUser findUserByLoginName(String loginName) {
		return loginUseOnlyUserDao.findByLoginName(loginName);
	}

	/**
	 * 取出Shiro中的当前用户LoginName.
	 */
	protected String getCurrentUserName() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.loginName;
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	protected void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}

	@Autowired
	public void setLoginUseOnlyUserDao(LoginUseOnlyUserDao loginUseOnlyUserDao) {
		this.loginUseOnlyUserDao = loginUseOnlyUserDao;
	}
}
